package com.example.myapplication;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import com.example.myapplication.broadcast.SendMsgReceiver;
import com.example.myapplication.databinding.ActivityMainBinding;
import com.example.myapplication.jet.UserViewModel;

public class MainActivity extends BaseActivity {

    private UserViewModel viewModel;
    private ActivityMainBinding binding;
    private SendMsgReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        viewModel = new ViewModelProvider(this, new SavedStateViewModelFactory()).get(UserViewModel.class);
        binding.setData(viewModel);

        // 注册广播
        registerBroadcast();
        Button castBtn = findViewById(R.id.send_cast_btn);
        castBtn.setOnClickListener(v -> {
            Intent intent = new Intent("com.liao.wei.broadcast");
            intent.putExtra("msg", "BroadCast");
            sendBroadcast(intent);
            // sendOrderedBroadcast(intent, null); // 有序广播
        });

        binding.setLifecycleOwner(this);
    }

    public void registerBroadcast() {
        IntentFilter intentFilter = new IntentFilter("com.liao.wei.broadcast");
        receiver = new SendMsgReceiver();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}